package com.business.systemmanage.common.interceptor;

import com.business.systemmanage.common.entity.ResponseInfo;
import io.netty.util.internal.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class RedisSessionInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate redisTemplate;
    private final boolean debug_flag = Boolean.FALSE;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (debug_flag) {
            System.out.println("开发模式不校验登陆");
            return Boolean.TRUE;
        }
        try {
            String token = request.getHeader("token");
            String redisUserId = redisTemplate.opsForValue().get(token);
            if (!StringUtils.isEmpty(redisUserId)) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        response401(response);
        return false;
    }

    private void response401(HttpServletResponse response) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");

        try {
            Map<String, String> resultMap = new HashMap<>();
            response.getWriter().print(ResponseInfo.generateErrorRes("请重新登陆"));
            //后期统一跳转页面
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

}
